package cn.shop.cloud.service.impl;

import cn.shop.cloud.common.BusinessException;
import cn.shop.cloud.domain.User;
import cn.shop.cloud.mapper.UserMapper;
import cn.shop.cloud.redis.MemberServerKeyPrefix;
import cn.shop.cloud.redis.MyRedisTemplate;
import cn.shop.cloud.service.UserService;
import cn.shop.cloud.web.msg.MemberCodeMsg;
import cn.shop.cloud.web.util.MD5Util;
import cn.shop.cloud.web.vo.LoginVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;


/**
 * @program: xiangmu
 * @ClassName UserService
 * @description:
 * @author: 李尧坤
 * @create: 2024−12-14 09:36
 * @Version 1.0
 **/
@Service
public class UserServiceImpl  implements UserService, InitializingBean {

    @Autowired
    private UserMapper userMapper;

    @Autowired//从spring容器中获取指定的类型，如果找到就进行注入，如果找不到，抛出异常
    private MyRedisTemplate myRedisTemplate;

    @Override
    public User find(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public String login(LoginVo loginVo) {

/*        //临时过渡一下的方法
        if(StringUtils.isEmpty(loginVo.getPassword())){
            //如果账号或者密码一个为空，就抛异常
            throw new BusinessException(MemberCodeMsg.OP_ERROR);
        }*/

        //jsr 303  上方代码无用
        /*
              1. 添加依赖
              2.实体类上添加注解校验规则
              3.控制器的方法的形参上面添加  @Valid

         */
        //根据手机号查询用户信息
        User user = this.find(Long.parseLong(loginVo.getUsername()));

        if (user == null) {
            //账号或者密码错误
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }

        //数据库中的密码是加密的
        String encodePwd = MD5Util.encode(loginVo.getPassword(), user.getSalt());
        //对比密码
        if(!user.getPassword().equals(encodePwd)){
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }

        String token = createToken(user);


        return token;
    }

    @Override
    public User getUserByToken(String token) {
        return myRedisTemplate.get(MemberServerKeyPrefix.USER_TOKEN,token,User.class);
    }

    private String createToken(User user) {

        String token = UUID.randomUUID().toString().replace("-", "");

        //调用设置方法 自定义stater的添加方法
        myRedisTemplate.set(MemberServerKeyPrefix.USER_TOKEN,token,user);
        ////真正的key  realyKey = MemberServerKeyPrefix.USER_TOKEN+token

        return token;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //会在所有的配置装载完毕后自动调用这个方法
        /**
         * 解决分布式session的方案是：redis+token
         */
        System.out.println("=====================>"+ myRedisTemplate);
    }
}